package itbour.onetouchshow.utils.crop;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import itbour.onetouchshow.utils.crop.image.EnjoyImageView;


/**
 * 裁剪功能主要容器
 */
public class EnjoyCropLayout extends FrameLayout {
    private BaseLayerView mLayerView;
    private EnjoyImageView mImageView;

    /**
     * 是否限制边界
     */
    private boolean isRestrict;
    private int mFillColor;

    public EnjoyCropLayout(Context context) {
        super(context);
        init();
    }

    public EnjoyCropLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    /**
     * 是否限制边界
     *
     * @return
     */
    public boolean isRestrict() {
        return isRestrict;
    }

    /**
     * 限制边界
     *
     * @param restrict
     */
    public void setRestrict(boolean restrict, int width, int height) {
        isRestrict = restrict;
        if (isRestrict) {
            setRestrict(width, height);
        } else {
            mImageView.setRestrictBound(null);
        }
    }

    public int getFillColor() {
        return mFillColor;
    }

    /**
     * 设置超出边界时候的填充颜色
     *
     * @param fillColor
     */
    public void setFillColor(int fillColor) {
        this.mFillColor = fillColor;
    }

    /**
     * 初始化裁剪所需组件，并且添加到容器中
     */

    private void init() {
        mImageView = new EnjoyImageView(getContext());
        mImageView.setScaleType(ImageView.ScaleType.MATRIX);
        mFillColor = Color.BLACK;
    }

    public void setLayerView(BaseLayerView layerView) {
        if (mLayerView != null) {
            removeView(mLayerView);
        }
        if (mImageView != null) {
            removeView(mImageView);
        }
        addView(mImageView);
        addView(layerView, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        mLayerView = layerView;
    }


    private void setRestrict(final int width, final int height) {

        post(new Runnable() {
            @Override
            public void run() {
                if (mLayerView == null) {
                    return;
                }
                int centerX = (mLayerView.getLeft() + mLayerView.getRight()) / 2;
                int centerY = (mLayerView.getTop() + mLayerView.getBottom()) / 2;
                int shapeLeft = centerX - mLayerView.getShape().width() / 2;
                int shapeRight = centerX + mLayerView.getShape().width() / 2;
                int shapeTop = centerY - mLayerView.getShape().height() / 2;
                int shapeBottom = centerY + mLayerView.getShape().height() / 2;
//                RectF rectF = new RectF(shapeLeft,shapeTop,shapeRight,shapeBottom);
                RectF rectF = new RectF(shapeLeft + width, shapeTop + height, shapeRight - width, shapeBottom - height);
                mImageView.setRestrictBound(rectF);
            }
        });


    }


    /**
     * 设置将裁剪的图片
     *
     * @param resId
     */
    public void setImageResource(int resId) {
        mImageView.setImageResource(resId);
    }

    /**
     * 设置将裁剪的图片
     *
     * @param bitmap
     */
    public void setImage(Bitmap bitmap) {
        mImageView.setImageBitmap(bitmap);
    }

    /**
     * 给第三方图片加载提供引用
     *
     * @return
     */
    public ImageView getImageView() {
        return mImageView;
    }


    /**
     * 裁剪
     */
    public Bitmap crop(float maxWidth, float maxHeight) {

        if (mLayerView == null) {
            Log.e("EnjoyCropLayout", " layerView is null");
        }
        if (mImageView.getDrawable() == null) {
            Log.e("EnjoyCropLayout", "ImageView 'drawable is null");
            return null;
        }
        if (!(mImageView.getDrawable() instanceof BitmapDrawable)) {
            Log.e("EnjoyCropLayout", "only support the type of BitmapDrawable");
            return null;
        }
        IShape iShape = mLayerView.getShape();
        if (iShape == null) {
            Log.e("EnjoyCropLayout", "shape is null");
            return null;
        }

        BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable();
        Bitmap bitmap = drawable.getBitmap();
//        //缩小图片到裁剪框比例宽高 高最大为服务器返回的高*1.5
//        if (bitmap.getHeight()>maxHeight){
//            Matrix matrix = new Matrix();
//            matrix.setScale(maxHeight/bitmap.getHeight(), maxHeight/bitmap.getHeight());
//            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
//                    bitmap.getHeight(), matrix, true);
//        }
//        //缩小图片到裁剪框比例宽高 宽最大为服务器返回的宽*1.5
//        if (bitmap.getWidth()>maxWidth){
//            Matrix matrix = new Matrix();
//            matrix.setScale(maxWidth/bitmap.getWidth(), maxWidth/bitmap.getWidth());
//            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
//                    bitmap.getHeight(), matrix, true);
//        }
        if (bitmap == null) {
            Log.e("EnjoyCropLayout", "bitmap is null");
            return null;
        }
        //以下所有步骤的思路，均是将点或者大小还原到加载图片大小比例后，再进行处理。
        int cropLeft = 0, cropTop = 0;
        double scale = mImageView.getScale();
        //获取裁剪区域的实际长宽
        int actuallyWidth = (int) (iShape.width() * 1.0 / scale);
//        if (actuallyWidth>maxWidth){
//            actuallyWidth=(int)maxWidth;
//        }
        int actuallyHeight = (int) (iShape.height() * 1.0 / scale);
//        if (actuallyHeight>maxHeight){
//            actuallyHeight=(int)maxHeight;
//        }
        //重新计算得出最终裁剪起始点
        cropLeft = (int) (bitmap.getWidth() / 2 - mImageView.getActuallyScrollX() / scale - actuallyWidth / 2);
        cropTop = (int) (bitmap.getHeight() / 2 - mImageView.getActuallyScrollY() / scale - actuallyHeight / 2);

        //  Bitmap newBitmap = Bitmap.createBitmap(bitmap,centerX,centerY,actuallyWidth,actuallyHeight);
        //保存的图片
        Bitmap saveBitmap = null;
        try {
            saveBitmap = Bitmap.createBitmap(actuallyWidth, actuallyHeight, Bitmap.Config.ARGB_4444);
        } catch (OutOfMemoryError e) {
//            scale=maxHeight/bitmap.getHeight();
            actuallyWidth = iShape.width();
            actuallyHeight = iShape.height();
            //取整之后减去1px偏移量
            cropLeft = (int) (bitmap.getWidth() * scale / 2 - mImageView.getActuallyScrollX() - actuallyWidth / 2) - 1;
            cropTop = (int) (bitmap.getHeight() * scale / 2 - mImageView.getActuallyScrollY() - actuallyHeight / 2) - 1;
            saveBitmap = Bitmap.createBitmap(actuallyWidth, actuallyHeight, Bitmap.Config.ARGB_4444);
            Canvas canvas = new Canvas(saveBitmap);
            int showRight = actuallyWidth;
            int showBottom = actuallyHeight;
            int cropRight = cropLeft + actuallyWidth;
            int cropBottom = cropTop + actuallyHeight;
            if (cropRight > bitmap.getWidth() * scale) {
                cropRight = (int) (bitmap.getWidth() * scale);
                showRight = (int) (bitmap.getWidth() * scale - cropLeft);
                saveBitmap.setHasAlpha(true);
            } else {
                saveBitmap.setHasAlpha(true);
            }
            if (cropBottom > bitmap.getHeight() * scale) {
                cropBottom = (int) (bitmap.getHeight() * scale);
                showBottom = (int) (bitmap.getHeight() * scale - cropTop);
            }
            Rect cropRect = new Rect(cropLeft, cropTop, cropRight, cropBottom);
            Rect showRect = new Rect(0, 0, showRight, showBottom);
            Matrix matrix = new Matrix();
            //float scl=(float) (bitmap.getHeight()*scale/bitmap.getHeight());
            matrix.setScale((float) scale, (float) scale);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), matrix, true);
            canvas.drawBitmap(bitmap, cropRect, showRect, new Paint());

            return saveBitmap;
        }


        Canvas canvas = new Canvas(saveBitmap);
        //当裁剪超出图片边界，超出区域以颜色填充
//        canvas.drawColor(mFillColor);
        //计算显示与实际裁剪的大小
        int showRight = actuallyWidth;
        int showBottom = actuallyHeight;
        int cropRight = cropLeft + actuallyWidth;
        int cropBottom = cropTop + actuallyHeight;
        //裁剪超出图片边界超出边界
        if (cropRight > bitmap.getWidth()) {
            cropRight = bitmap.getWidth();
            showRight = bitmap.getWidth() - cropLeft;
            saveBitmap.setHasAlpha(true);
        } else {
            saveBitmap.setHasAlpha(true);
        }
        if (cropBottom > bitmap.getHeight()) {
            cropBottom = bitmap.getHeight();
            showBottom = bitmap.getHeight() - cropTop;
        }
        Rect cropRect = new Rect(cropLeft, cropTop, cropRight, cropBottom);
        Rect showRect = new Rect(0, 0, showRight, showBottom);
        canvas.drawBitmap(bitmap, cropRect, showRect, new Paint());

        return saveBitmap;

    }


//    /**
//     * 设置默认的半透明背景，方形预览框
//     * @param squareWidth 方形预览框宽度
//     */
//    public void setDefaultSquareCrop(int squareWidth){
//
//        BaseLayerView layerView = new ClipPathLayerView(getContext());
//        layerView.setMask(ColorMask.getTranslucentMask());
//        layerView.setShape(new ClipPathSquare(squareWidth));
//        setLayerView(layerView);
//        setRestrict(true,0,0);
//    }
//
//    /**
//     * 设置默认的半透明背景，圆形预览框
//     * @param radius 圆形预览框半径
//     */
//    public void setDefaultCircleCrop(int radius){
//
//        BaseLayerView layerView = new ClipPathLayerView(getContext());
//        layerView.setMask(ColorMask.getTranslucentMask());
//        layerView.setShape(new ClipPathCircle(radius));
//        setLayerView(layerView);
//        setRestrict(true,0,0);
//    }


}
